<!-- 挽留弹窗 -->
<template>
  <div class="keep_back">
    <van-popup v-model:show="internalShow" class="keep_back_popup" @close="closeBtn">
      <div class="inner_content">
        <div class="top">
          <img src="@/assets/images/ic_back@2x.png" @click="closeBtn" />
        </div>
        <div class="title">New Friend Offer</div>
        <div class="sub_title">Just this once</div>
        <div class="wrap_img">
          <img src="@/assets/images/pic_tv@2x.png" alt="" />
          <!-- 定位文字到图片上 -->
          <div class="img_top_block">
            <div class="left_block">50</div>
            <div class="right_block">
              <div class="pencent">%</div>
              <div class="off">OFF</div>
            </div>
          </div>
          <div class="img_bottom_block">
            <div class="word_top" style="text-decoration: line-through;">$9.98</div>
            <div class="word_bottom">$4.99</div>
          </div>
          <!-- 定时器 -->
          <div class="countdown-container">
            <van-count-down :time="timeMs" millisecond class="time_text" @finish="handleCountdownFinish">
              <template #default="{ minutes, seconds }">
                <span class="time-item minute">{{ formatTime(minutes) }}</span>
                <span class="time-item second">{{ formatTime(seconds) }}</span>
              </template>
            </van-count-down>
          </div>
          <div class="minutes_second">
            <span class="minutes_text">Minute</span>
            <span class="seconds_text">Second</span>
          </div>
          <!-- 左上角的 -->
          <div class="right_top_box">
            <img src="@/assets/images/ic_star_24@2x.png" class="star_24" />
            <span class="gems_text">500 gems</span>
          </div>
        </div>
        <button class="comfirmBtn" @click="getDiscount">Get Discounts</button>
      </div>
    </van-popup>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from "vue";
import { trackEvent } from "@/utils/firebase";
import { showToast } from "vant";
import api from "@/api";
import { getStripe } from "@/utils/stripe";

const props = defineProps(["show"]);
const emit = defineEmits(["close"]);
const internalShow = ref(false); // 初始值

const formatTime = (val) => val.toString().padStart(2, "0");

// 监听父组件 show 变化
watch(
  () => props.show,
  (newVal) => {
    internalShow.value = newVal;
    //console.log("子组件同步更新:", internalShow.value); // 调试输出
    queryOrderTime()
    if (internalShow.value) {
      trackEvent("展示_挽留页", { id: "100011" });
    }
  }
);

const discountStatus = ref(false)
// 从接口获取的毫秒数
const timeMs = ref(30000); // 默认30秒
// 倒计时
const queryOrderTime = async () => {
  try {
    const res = await api.orderCountdown();
    if (res.data?.remainingSeconds) {
      timeMs.value = (res.data.remainingSeconds) * 1000
    }
  } catch (err) {
    console.log(err);
  }
};
// 倒计时结束
const handleCountdownFinish = () => {
  discountStatus.value = true;
}

// 支付
const getDiscount = async () => {
  trackEvent("挽留页_点击 Get Discounts", { id: "100012" });
  if (discountStatus.value) {
    showToast("Sorry, you are late");
    return
  }
  const prevRoute = JSON.parse(sessionStorage.getItem("prevRoute"));
  const referrerUrl = prevRoute ? prevRoute.fullPath : "/";
  // 创建订单
  try {
    const res = await api.orderCreate({
      amount: 500,
    });
    // 获取会话
    const getClickId = localStorage.getItem("click_id");
    stripeSession({
      orderId: res.data.orderId,
      returnUrl: encodeURIComponent(referrerUrl),
      clickId: getClickId,
      ct: 'checkout'
    }); // 对returnUrl进行编码
  } catch (err) {
    console.log(err);
  }
};

// 会话
const stripeSession = async (params) => {
  try {
    const res = await api.stripeSession(params);
    toCheckout(res.data.publicKey, res.data.sessionId);
  } catch (err) {
    console.log(err);
  }
};

// 支付相关
const toCheckout = async (publicKey, sessionId) => {
  try {
    const stripe = await getStripe(publicKey);
    // 使用 Stripe SDK 提供的跳转方法
    const { error } = await stripe.redirectToCheckout({
      sessionId: sessionId,
    });

    if (error) {
      console.error("跳转失败:", error);
    }
  } catch (err) {
    console.error("Stripe 加载失败:", err);
  }
};
// 关闭
const closeBtn = () => {
  emit("close");
};

// 初始化时同步父组件值
onMounted(() => {
  internalShow.value = props.show;
  if (internalShow.value) {
    queryOrderTime();
    trackEvent("展示_挽留页", { id: "100011" });
  }
});
</script>

<style scoped lang="less">
.right_top_box {
  width: 140px;
  height: 40px;
  background: linear-gradient(90deg, #6251ff 0%, #516eff 100%);
  border-radius: 20px 20px 20px 20px;
  border: 4px solid #ffffff;
  position: absolute;
  top: 4px;
  right: 10px;
  display: flex;
  justify-content: center;
  align-items: center;

  .star_24 {
    width: 24px !important;
  }

  .gems_text {
    font-weight: bold;
    font-size: 18px;
    color: #ffffff;
    margin-left: 2px;
  }
}

.keep_back {

  // width: 100vw;
  // height: 100vh;
  // overflow-y: auto;
  :deep(.keep_back_popup) {
    width: 100% !important;
    height: 100% !important;
    padding: 0 !important;
    /* 清除内边距 */
    margin: 0 !important;
    /* 清除外边距 */
    border-radius: 0 !important;
    /* 可选：去除圆角 */
    max-width: 100vw;
    box-sizing: border-box;
    /* 背景图设置 */
    background-image: url("../assets/images/bg_texture@2x.png");
    background-position: top center;
    /* 从顶部开始 */
    background-repeat: no-repeat;
    /* 不重复 */
    background-size: 100% auto;
    /* 宽度满屏，高度自适应 */
    background-color: #fbfbfd;

    .inner_content {
      box-sizing: border-box;
      padding: 0 16px;
      padding-bottom: 50px;
    }

    .top {
      width: 100%;
      height: 56px;
      display: flex;
      justify-content: left;
      align-items: center;

      img {
        width: 24px;
      }
    }
  }

  .title {
    text-align: center;
    font-size: 32px;
    line-height: 39px;
    color: rgba(0, 0, 0, 0.95);
    font-weight: 700;
  }

  .sub_title {
    font-size: 22px;
    color: rgba(0, 0, 0, 0.75);
    text-align: center;
  }

  .wrap_img {
    width: 280px;
    margin: 0 auto;
    position: relative;

    img {
      width: 100%;
    }

    .img_top_block {
      position: absolute;
      left: 64px;
      top: 30px;
      display: flex;
      justify-content: center;
      align-items: center;

      .left_block {
        font-weight: bold;
        font-size: 81px;
        color: #ffffff;
      }

      .right_block {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;

        .pencent {
          font-weight: bold;
          font-size: 48px;
          color: #ffffff;
          height: 60px;
        }

        .off {
          font-weight: bold;
          font-size: 18px;
          color: #ffffff;
        }
      }
    }

    .img_bottom_block {
      width: 230px;
      border-top: 1px dashed #fff;
      position: absolute;
      left: 28px;
      top: 150px;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      text-align: center;
      padding-top: 4px;

      .word_top {
        font-size: 16px;
        color: rgba(255, 255, 255, 0.65);
        line-height: 16px;
        margin-bottom: 2px;
      }

      .word_bottom {
        font-weight: bold;
        font-size: 24px;
        color: #ffffff;
        line-height: 24px;
      }
    }
  }

  .pay_wrap_block {
    width: 344px;
    height: 102px;
    background: rgba(255, 255, 255, 0.45);
    box-shadow: inset 0px 1px 0px 0px rgba(255, 255, 255, 0.45);
    border-radius: 12px;
    margin: 0 auto;
    box-sizing: border-box;
    padding: 8px 12px;

    .pay_title {
      text-align: center;
      font-size: 16px;
      color: rgba(0, 0, 0, 0.95);
      margin-bottom: 3px;
    }
  }

  .pay_ul {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .pay_li {
      width: 74px;
      height: 56px;
      background: linear-gradient(180deg,
          rgba(255, 255, 255, 0.85) 0%,
          rgba(255, 255, 255, 0.45) 100%);
      border-radius: 8px;
      display: flex;
      justify-content: center;
      align-items: center;

      img {
        width: 74px;
      }
    }

    .pay_li:first-child {
      img {
        width: 48px;
      }
    }

    .activeLi {
      border: 1px solid #6251ff;
    }
  }

  .comfirmBtn {
    width: 100%;
    height: 64px;
    background: linear-gradient(90deg, #ffd52f 0%, #f874ff 50%, #516eff 100%);
    box-shadow: 0px 4px 4px 0px rgba(0, 20, 244, 0.16);
    border-radius: 8px;
    border: 0;
    text-align: center;
    line-height: 64px;
    font-size: 20px;
    color: #ffffff;
    // margin-top: 16px;
    margin-top: 26px;
  }
}

.countdown-container {
  position: absolute;
  left: 0;
  bottom: 10px;
  width: 100%;
  height: 50px;
  margin: 20px auto;
}

.time-text {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.time-item {
  position: absolute;
  width: 40%;
  text-align: center;
  font-size: 18px;
  font-weight: 700;
  color: #ffffff;
  transition: all 0.3s ease;
}

.minute {
  left: 50px;
  top: 16px;
}

.second {
  right: 50px;
  top: 16px;
}

.minutes_second {
  width: 100%;
  height: 20px;
  position: absolute;
  left: 0;
  bottom: 24px;

  .minutes_text {
    position: absolute;
    left: 90px;
    font-size: 10px;
    color: #fff;
  }

  .seconds_text {
    position: absolute;
    right: 90px;
    font-size: 10px;
    color: #fff;
  }
}
</style>
